'use strict';

// 测试云函数
// 调用公共函数
const v = require('ver');
exports.main = async (event, context) => {
    console.log('event', event);
    console.log('context', context);

    const {
        path,
        queryStringParameters
    } = event;
    let {
        title,
        content
    } = queryStringParameters;

    const db = uniCloud.database();
    switch (path) {
        case '/add': {
            if (!title || !content) {
                return {
                    errCode: 100,
                    errMsg: '标题或内容不可为空'
                }
            }
            title = title.trim()
            content = content.trim()
            let now = new Date().getTime();

            let new_row = await db.collection('msg').add({
                title: v(title),
                content: content + ' ' + now,
                status: true
            });
            let effect_num = new_row.inserted;
            console.log(new_row, effect_num);
            if (effect_num > 0)
                return {
                    errCode: 0,
                    errMsg: '创建成功',
                    data: new_row
                }
            else
                return {
                    errCode: 200,
                    errMsg: '创建失败'
                }
        };
    case '/view': {
        let data = await db.collection('msg').get();

        return {
            errCode: 0,
            errMsg: '列表',
            data: data
        }
    };
    case '/obj_test': {
        const test2 = uniCloud.importObject('test2');
        const res = await test2.add('title demo', 'content demo')
        return {
            errCode: 0,
            errMsg: '云对象-测试',
            data: res
        }
    };

    }
    return {
        errCode: -1,
        errMsg: `方法[${path}]不存在`
    }
};
